<?php

namespace app\api\controller;

use app\common\lib\Sms;

class Mess extends Basic
{
    public function __construct($option = array())
    {
    }

    public function index()
    {
        $type = input('type', 1);
        $mobile = input('mobile', 0);
        $reg = input("reg", 1);

        if (empty($mobile)) {
            return $this->json($mobile, 2000, '请传入手机号码');
        }

        if ($type == 1) {
            $tableName = 'member';
            // $where = [
            //     'membermobile' => $mobile
            // ];
        } else {
            $tableName = 'coach';
            // $where = [
            //     'coachmobile' => $mobile
            // ];
        }

        // $info = $this->findTable($tableName, ['where' => $where]);

        /**
         * 验证码登录  reg=1
         * 注册  reg=2
         * 修改密码  reg=3
         */
        // if ($reg == 1) {
        //     if (empty($info)) {
        //         return $this->json($info, 2000, '用户不存在，请前往注册页面进行注册');
        //     }
        // } else if ($reg == 2) { //手机注册判定
        //     if (!empty($info)) {
        //         if ($info['status'] == 1) {
        //             return $this->json([], 2000, '该用户已存在，请登录');
        //         } else if ($info['status'] == 0) {
        //             return $this->json([], 2000, '该用户已被暂停使用，请联系客服');
        //         }
        //     }
        // } else if($reg == 3) {
        //     if (empty($info)) {
        //         return $this->json($info, 2000, '账户不存在，请前往注册页面进行注册');
        //     }
        // }

        $code = $this->random(4, true);
        $params['signName'] = config('param.alimess.signName');
        $params['templateCode'] = config('param.alimess.templateCode');
        $arr = $this->sendMessByAli($mobile, $code, $params);
        if ($arr && $arr['Code'] == 'OK') {
            $data['abouttable'] = $tableName;
            $data['mobile'] = $mobile;
            $data['code'] = $code;
            $data['ip'] = get_ip();
            $data['msg'] = json_encode($params, true);
            $data['type'] = $reg;
            $ans = $this->insertTable('message_log', $data);
            if ($ans) {
                return $this->json($arr, 1000);
            } else {
                return $this->json($arr, 2000);
            }
        } else {
            return $this->json($arr, 2008, empty($arr['Message']) ? '短信异常' : $arr['Message']);
        }
    }

    /**
     * 获取验证码
     */
    public function random($length, $numeric = false)
    {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed{
                mt_rand(0, $max)};
        }
        return $hash;
    }

    /**
     * 验证码验证
     *
     */
    public function very()
    {
        $mobile = input("mobile", 0);
        $type = input("type", 1);
        $reg = input("reg", 0);
        $code = input("code", 0);

        if (!$mobile || !$type || !$code) {
            return $this->json([], 2000);
        }

        if ($type == 1) {
            $tableName = 'member';
            $twhere = [
                'membermobile' => $mobile,
            ];
        } else {
            $tableName = 'coach';
            $twhere = [
                'coachmobile' => $mobile,
            ];
        }

        $exetime = $this->time();
        $where = [];
        $where['abouttable'] = $tableName;
        $where['mobile'] = $mobile;
        $where['code'] = $code;
        $where['isdel'] = 0;
        $where['status'] = 1;

        $info = $this->findTable('message_log', ['where' => $where]);
        if ($info) {
            if ((time() - $info['addtime']) > $exetime) {
                return $this->json(['mobile' => $info, 'code' => $code], 2000, '验证码已失效');
            } else {
                $update = [
                    'where' =>['logid' => $info['logid']],
                    'data' => ['status' => 0],
                ];

                $ans = $this->updateTable('message_log', $update);
                if ($ans) {
                    if ($reg == 1) {
                        $info = $this->findTable($tableName, ['where' => $twhere]);
                        if(empty($info)) {
                            return $this->json([], 2000, '用户不存在');
                        }
                        $isbool = 0;
                        if($type == 1) {
                            if ($info['status'] == 0) {
                                return $this->json([], 2000, '该用户已被禁止使用，请联系客服');
                            } else if($info['status'] == 2) {
                                return $this->json([], 2000, '当前账号未激活，请前往注册页面进行注册激活');
                            } else if ($info['status'] == 4) {
                                if ($info['lockingtime'] != 1) {
                                    if ($info['lockingtime'] >= time()) {
                                        $where == ['memberid' => $info['memberid']];
                                        $update = [
                                            'where' => $where,
                                            'data' => ['status' => 1, 'lockingtime' => 0],
                                        ];
                                        $id = $info['memberid'];
                                        $this->updateTable('member', $update);
                                    }
                                } else {
                                    return $this->json([], 2000, '该用户已被暂停使用，请联系客服');
                                }
                            }
                            
                        } else {
                            if ($info['status'] == 0) {
                                return $this->json([], 2000, '该用户已被禁止使用，请联系客服');
                            } else if ($info['status'] == 5) {
                                if ($info['lockingtime'] != 1) {
                                    if ($info['lockingtime'] >= time()) {
                                        $where = ['coachid' => $info['coachid']];
                                        $update = [
                                            'where' => $where,
                                            'data' => ['status' => 3, 'lockingtime' => 0],
                                        ];
                                        $id = $info['coachid'];
                                        $this->updateTable('coach', $update);
                                    }
                                } else {
                                    return $this->json([], 2000, '该用户已被暂停使用，请联系客服');
                                }
                            }
                            
                            if($info['status'] == 1) {
                                $isbool = 1;
                            }
                        }
                        $key = $tableName . 'id';
                        $token = $this->getToken($tableName, $info, $info[$key]);
                        if ($token) {
                            return $this->json(['token' => $token, 'isbool'=>$isbool], 1000);
                        } else {
                            return $this->json([], 2000, '登录失败');
                        }
                    } else {
                        return $this->json([], 1000, '验证通过');
                    }
                } else {
                    return $this->json(['mobile' => $mobile, 'code' => $code, 'info' => $info], 2000, '验证异常');
                }
            }
        } else {
            return $this->json(['mobile' => $mobile, 'code' => $code], 2000, '验证码错误');
        }
    }


    public function sendMessByAli($mobile, $code, $params)
    {
        $aliMess = new Sms(config('param.alimess.accessKeyId'), config('param.alimess.accessSecret'));
        $ans = $aliMess->sendAuthCode($mobile, $code, $params);
        return $ans;
    }

    public function sendNoticeByAli($mobile, $templateparam, $params)
    {
        $aliMess = new Sms(config('param.alimess.accessKeyId'), config('param.alimess.accessSecret'));
        $ans = $aliMess->sendNoticeSms($mobile, $templateparam, $params);
        return $ans;
    }

    public function aa()
    {
        $params = [];
        $params['signName'] = '快通驾驶';
        $params['noticetemplateCode'] = "SMS_189032233";
        $mess = new Mess();
        $res = $mess->sendNoticeByAli(15676120064, ['consignee'=>'asdfs', 'number'=>'13144138297'], $params);
        dump($res);
    }

    /**
     * 获取短信码失效时间
     */
    public function time()
    {
        return 30 * 60;
    }
}
